# -*- coding: utf-8 -*-

"""
自定义django模版标签
"""

from django import template
from django.db.models.aggregates import Count

from ..models import Article, Category, Tag

register = template.Library()


@register.assignment_tag
def get_recent_articles(num=5):
    """最新文章模板标签"""
    return Article.objects.all()[:num]


@register.assignment_tag
def get_archives():
    """
    归档模板标签
    描述：mysql在windows系统没有时区信息数据库，则需要使用mysql_tzinfo_to_sql程序用来装载时区表
    参考：1. http://blog.chinaunix.net/uid-20648934-id-1592747.html
          2. https://dev.mysql.com/downloads/timezones.html
    """
    return Article.objects.datetimes('created_time', 'month', order='DESC')


@register.assignment_tag
def get_categories():
    """分类模板标签：按分类统计文章数量"""
    return Category.objects.annotate(article_count=Count('article')).filter(article_count__gt=0)

@register.assignment_tag
def get_tags():
    """标签模版：按标签统计文章数量"""
    return Tag.objects.annotate(article_count=Count('article')).filter(article_count__gt=0)
